<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class RequestManager {
	
    private static $m_pInstance; 
    private function __construct() {} 
    private $data = array();
    private $send_type = "";
    private $access_path = "";

    public static function getInstance() 
    { 
        if (!self::$m_pInstance) 
        { 
            self::$m_pInstance = new RequestManager(); 
        } 
        return self::$m_pInstance; 
    } 
	
	public function setData($data=array()){
		$this->data = $data;
	}
	
	public function setSendType($type="rest"){
		$this->send_type = $type;
	}
	
	public function setAccessPath($path){
		$this->access_path = $path;
	}
	
	public function send(){
		$path = array();
		$url = "";
		$ch = curl_init();
		switch($this->send_type){
			case 'rest':
				foreach($this->data as $name=>$value){
					$path[] = $value;
				}
				if(!empty($path)){
					$url = implode($path, "/");
				}
				break;
				
			case 'post':
				//var_dump($this->data);
				curl_setopt( $ch, CURLOPT_POST, 1 );
				curl_setopt( $ch, CURLOPT_POSTFIELDS, $this->data );
				break;
				
			case 'get':
				$url = http_build_query($this->data,'','&');
				break;
		}
		$service_url = $this->access_path . "/". $url;
		//echo $service_url;
		try {
			curl_setopt( $ch, CURLOPT_URL, $service_url);
			curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
			curl_setopt( $ch, CURLOPT_HEADER, 0 );
			$res_string = curl_exec($ch);
			$rexpo_response = $res_string;
			//echo $rexpo_response;
			$output = json_decode($rexpo_response);
			curl_close($ch);
		} catch (Exception $e) {
			throw new Exception('Cannot perform this process',0,$e);
		}
		return $output;
	
	}
	
	public function getData(){
		return $this->data;
	}
}